<!-- 地图容器组件 - 集成Cesium和OpenLayers -->
<template>
  <div class="map-container">
    <!-- 地图模式切换 -->
    <div class="map-mode-switch">
      <el-radio-group v-model="mapMode" size="small" @change="switchMapMode">
        <el-radio-button label="2d">
          <el-icon><Grid /></el-icon>
          二维态势
        </el-radio-button>
        <el-radio-button label="3d">
          <el-icon><Box /></el-icon>
          三维地球
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 地图控制工具栏 -->
    <div class="map-toolbar">
      <div class="toolbar-group">
        <el-button size="small" @click="zoomIn">
          <el-icon><ZoomIn /></el-icon>
        </el-button>
        <el-button size="small" @click="zoomOut">
          <el-icon><ZoomOut /></el-icon>
        </el-button>
        <el-button size="small" @click="resetView">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
      
      <div class="toolbar-group">
        <el-button size="small" @click="toggleFullscreen">
          <el-icon><FullScreen /></el-icon>
        </el-button>
        <el-button size="small" @click="toggleMeasure">
          <el-icon><Operation /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 图层控制面板 -->
    <div class="layer-panel" :class="{ collapsed: layerPanelCollapsed }">
      <div class="panel-header" @click="layerPanelCollapsed = !layerPanelCollapsed">
        <span class="panel-title">图层控制</span>
        <el-icon class="collapse-icon" :class="{ rotated: layerPanelCollapsed }">
          <ArrowDown />
        </el-icon>
      </div>
      
      <div v-show="!layerPanelCollapsed" class="panel-content">
        <div v-for="layer in mapLayers" :key="layer.id" class="layer-item">
          <el-switch
            v-model="layer.visible"
            size="small"
            @change="toggleLayer(layer)"
          />
          <span class="layer-name">{{ layer.name }}</span>
          <el-slider
            v-model="layer.opacity"
            :min="0"
            :max="100"
            size="small"
            class="layer-opacity"
            @change="updateLayerOpacity(layer)"
          />
        </div>
      </div>
    </div>

    <!-- 地图主容器 -->
    <div class="map-wrapper">
      <!-- 2D地图 (OpenLayers) -->
      <div
        v-show="mapMode === '2d'"
        ref="olMapRef"
        class="ol-map-container"
      ></div>
      
      <!-- 3D地图 (Cesium) -->
      <div
        v-show="mapMode === '3d'"
        ref="cesiumMapRef"
        class="cesium-map-container"
      ></div>
    </div>

    <!-- 坐标信息显示 -->
    <div class="coordinate-display">
      <div class="coord-item">
        <span class="coord-label">经度:</span>
        <span class="coord-value">{{ currentCoords.lon.toFixed(6) }}</span>
      </div>
      <div class="coord-item">
        <span class="coord-label">纬度:</span>
        <span class="coord-value">{{ currentCoords.lat.toFixed(6) }}</span>
      </div>
      <div v-if="mapMode === '3d'" class="coord-item">
        <span class="coord-label">高度:</span>
        <span class="coord-value">{{ currentCoords.height.toFixed(2) }}m</span>
      </div>
    </div>

    <!-- 绘制工具提示 -->
    <div v-if="drawMode" class="draw-tip">
      <el-alert
        :title="getDrawTipText()"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { 
  Grid, Box, ZoomIn, ZoomOut, Refresh, FullScreen, 
  Operation, ArrowDown 
} from '@element-plus/icons-vue'

// 导入地图库样式
import 'ol/ol.css'
import 'cesium/Build/Cesium/Widgets/widgets.css'

// 组件属性
const props = defineProps({
  drawMode: {
    type: String,
    default: ''
  },
  spatialFilter: {
    type: Object,
    default: () => ({})
  }
})

// 事件定义
const emit = defineEmits(['coordinates-change', 'draw-complete', 'area-selected'])

// 地图状态
const mapMode = ref('2d')
const olMapRef = ref(null)
const cesiumMapRef = ref(null)
const layerPanelCollapsed = ref(false)

// 当前坐标
const currentCoords = reactive({
  lon: 116.407526,
  lat: 39.904030,
  height: 0
})

// 地图图层配置
const mapLayers = ref([
  {
    id: 'base',
    name: '基础地图',
    visible: true,
    opacity: 100,
    type: 'base'
  },
  {
    id: 'satellite',
    name: '卫星影像',
    visible: false,
    opacity: 80,
    type: 'imagery'
  },
  {
    id: 'signals',
    name: '信号分布',
    visible: true,
    opacity: 70,
    type: 'data'
  },
  {
    id: 'threats',
    name: '威胁标识',
    visible: true,
    opacity: 90,
    type: 'data'
  },
  {
    id: 'coverage',
    name: '覆盖范围',
    visible: false,
    opacity: 50,
    type: 'analysis'
  }
])

// 地图实例
let olMap = null
let cesiumViewer = null
let drawHandler = null

// 地图初始化
const initMaps = async () => {
  await initOpenLayersMap()
  await initCesiumMap()
}

const initOpenLayersMap = async () => {
  try {
    // 动态导入OpenLayers
    const { Map, View } = await import('ol')
    const TileLayer = await import('ol/layer/Tile')
    const OSM = await import('ol/source/OSM')
    const { fromLonLat, toLonLat } = await import('ol/proj')

    // 确保容器存在
    if (!olMapRef.value) {
      console.warn('OpenLayers容器不存在')
      return
    }

    console.log('OpenLayers容器DOM:', olMapRef.value)

    olMap = new Map({
      target: olMapRef.value,
      layers: [
        new TileLayer.default({
          source: new OSM.default()
        })
      ],
      view: new View({
        center: fromLonLat([currentCoords.lon, currentCoords.lat]),
        zoom: 10
      })
    })

    console.log('OpenLayers地图初始化成功')

    // 监听鼠标移动获取坐标
    olMap.on('pointermove', (evt) => {
      const coordinate = toLonLat(evt.coordinate)
      currentCoords.lon = coordinate[0]
      currentCoords.lat = coordinate[1]
      emit('coordinates-change', { ...currentCoords })
    })

    // 监听点击事件
    olMap.on('click', (evt) => {
      handleMapClick(evt.coordinate, '2d')
    })

  } catch (error) {
    console.warn('OpenLayers初始化失败:', error)
    // 创建占位容器
    createMapPlaceholder(olMapRef.value, '2D地图', 'OpenLayers加载失败')
  }
}

const initCesiumMap = async () => {
  try {
    // 动态导入Cesium
    const Cesium = await import('cesium')
    
    // 确保容器存在
    if (!cesiumMapRef.value) {
      console.warn('Cesium容器不存在')
      return
    }

    console.log('Cesium容器DOM:', cesiumMapRef.value)

    // 设置Cesium静态资源路径
    window.CESIUM_BASE_URL = '/cesium/'
    
    // 设置Cesium Ion token (可选，用于在线资源)
    // Cesium.Ion.defaultAccessToken = 'your_token_here'
    
    cesiumViewer = new Cesium.Viewer(cesiumMapRef.value, {
      timeline: false,
      animation: false,
      baseLayerPicker: false,
      fullscreenButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: false,
      navigationHelpButton: false,
      navigationInstructionsInitiallyVisible: false,
      creditContainer: document.createElement('div') // 隐藏版权信息
    })

    // 设置初始视角
    cesiumViewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        currentCoords.lon, 
        currentCoords.lat, 
        1000000 // 调整高度
      )
    })

    console.log('Cesium地图初始化成功')

    // 监听鼠标移动
    const handler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.scene.canvas)
    handler.setInputAction((event) => {
      const cartesian = cesiumViewer.camera.pickEllipsoid(
        event.endPosition, 
        cesiumViewer.scene.globe.ellipsoid
      )
      if (cartesian) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
        currentCoords.lon = Cesium.Math.toDegrees(cartographic.longitude)
        currentCoords.lat = Cesium.Math.toDegrees(cartographic.latitude)
        currentCoords.height = cartographic.height
        emit('coordinates-change', { ...currentCoords })
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    // 监听点击事件
    handler.setInputAction((event) => {
      const cartesian = cesiumViewer.camera.pickEllipsoid(
        event.position, 
        cesiumViewer.scene.globe.ellipsoid
      )
      if (cartesian) {
        handleMapClick(cartesian, '3d')
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

  } catch (error) {
    console.warn('Cesium初始化失败:', error)
    // 创建占位容器
    createMapPlaceholder(cesiumMapRef.value, '3D地球', 'Cesium加载失败')
  }
}

const createMapPlaceholder = (container, title, message) => {
  container.innerHTML = `
    <div style="
      display: flex; 
      flex-direction: column; 
      align-items: center; 
      justify-content: center; 
      height: 100%; 
      background: rgba(45, 58, 75, 0.8);
      color: #bfcbd9;
      border: 2px dashed #2d3a4b;
      border-radius: 8px;
    ">
      <div style="font-size: 2em; margin-bottom: 10px;">🗺️</div>
      <div style="font-size: 1.2em; font-weight: bold; margin-bottom: 5px;">${title}</div>
      <div style="font-size: 0.9em; color: #8591a3;">${message}</div>
    </div>
  `
}

// 地图控制方法
const switchMapMode = (mode) => {
  mapMode.value = mode
  nextTick(() => {
    if (mode === '2d' && olMap) {
      olMap.updateSize()
    } else if (mode === '3d' && cesiumViewer) {
      cesiumViewer.resize()
    }
  })
}

const zoomIn = () => {
  if (mapMode.value === '2d' && olMap) {
    const view = olMap.getView()
    view.setZoom(view.getZoom() + 1)
  } else if (mapMode.value === '3d' && cesiumViewer) {
    cesiumViewer.camera.zoomIn(cesiumViewer.camera.positionCartographic.height * 0.5)
  }
}

const zoomOut = () => {
  if (mapMode.value === '2d' && olMap) {
    const view = olMap.getView()
    view.setZoom(view.getZoom() - 1)
  } else if (mapMode.value === '3d' && cesiumViewer) {
    cesiumViewer.camera.zoomOut(cesiumViewer.camera.positionCartographic.height * 0.5)
  }
}

const resetView = () => {
  if (mapMode.value === '2d' && olMap) {
    const view = olMap.getView()
    view.animate({
      center: [currentCoords.lon, currentCoords.lat],
      zoom: 10,
      duration: 1000
    })
  } else if (mapMode.value === '3d' && cesiumViewer) {
    cesiumViewer.camera.flyTo({
      destination: cesiumViewer.scene.globe.ellipsoid.cartographicToCartesian(
        new (window.Cesium || {}).Cartographic(
          (currentCoords.lon * Math.PI) / 180,
          (currentCoords.lat * Math.PI) / 180,
          100000
        )
      ),
      duration: 2.0
    })
  }
}

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    const container = mapMode.value === '2d' ? olMapRef.value : cesiumMapRef.value
    container.requestFullscreen()
  }
}

const toggleMeasure = () => {
  // 测量工具实现
  console.log('切换测量工具')
}

// 图层控制
const toggleLayer = (layer) => {
  // 根据地图类型和图层类型进行相应的显示/隐藏操作
  console.log(`切换图层: ${layer.name}, 可见性: ${layer.visible}`)
}

const updateLayerOpacity = (layer) => {
  // 根据地图类型和图层类型更新透明度
  console.log(`更新图层透明度: ${layer.name}, 透明度: ${layer.opacity}`)
}

// 地图交互处理
const handleMapClick = (coordinate, mapType) => {
  if (props.drawMode) {
    // 处理绘制模式下的点击
    handleDrawClick(coordinate, mapType)
  }
}

const handleDrawClick = (coordinate, mapType) => {
  let lonLat
  
  if (mapType === '2d') {
    // OpenLayers坐标转换
    lonLat = coordinate // 假设已经是经纬度
  } else {
    // Cesium坐标转换
    const cartographic = window.Cesium ? 
      window.Cesium.Cartographic.fromCartesian(coordinate) : 
      { longitude: 0, latitude: 0 }
    lonLat = [
      (cartographic.longitude * 180) / Math.PI,
      (cartographic.latitude * 180) / Math.PI
    ]
  }

  // 发送绘制点击事件
  emit('draw-complete', {
    coordinate: { lon: lonLat[0], lat: lonLat[1] },
    drawMode: props.drawMode
  })
}

// 工具方法
const getDrawTipText = () => {
  switch (props.drawMode) {
    case 'rectangle':
      return '点击地图绘制矩形选区'
    case 'circle':
      return '点击地图绘制圆形选区'
    case 'polygon':
      return '点击地图绘制多边形选区，双击完成'
    default:
      return '选择绘制工具开始绘制'
  }
}

// 监听绘制模式变化
watch(() => props.drawMode, (newMode) => {
  // 根据新的绘制模式设置地图交互
  console.log('绘制模式变更:', newMode)
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    console.log('开始初始化地图...')
    initMaps()
  })
})

onUnmounted(() => {
  if (drawHandler) {
    drawHandler.destroy()
  }
  if (olMap) {
    olMap.setTarget(null)
  }
  if (cesiumViewer && !cesiumViewer.isDestroyed()) {
    cesiumViewer.destroy()
  }
})
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #1f2d3d;
  border-radius: 0.8vw;
  overflow: hidden;
}

.map-mode-switch {
  position: absolute;
  top: 0.5vw;
  left: 5vw;
  z-index: 1002;
}

.map-mode-switch :deep(.el-radio-group) {
  display: flex;
  gap: 0;
}

.map-toolbar {
  position: absolute;
  top: 0.5vw;
  right: 1vw;
  z-index: 1001;
  display: flex;
  gap: 0.8vw;
  align-items: flex-start;
}

.toolbar-group {
  display: flex;
  gap: 0.5vw;
  background: rgba(31, 45, 61, 0.95);
  border-radius: 0.4vw;
  padding: 0.6vh 1vw;
  align-items: center;
  border: 1px solid #2d3a4b;
  height: 3.2vh;
  box-sizing: border-box;
}

.layer-panel {
  position: absolute;
  top: 2.5vw;
  right: 1vw;
  width: 18vw;
  max-width: 18vw;
  background: rgba(31, 45, 61, 0.95);
  border-radius: 0.6vw;
  z-index: 999;
  transition: all 0.3s ease;
  box-shadow: 0 0.4vw 1.2vw rgba(0, 0, 0, 0.3);
}

.layer-panel.collapsed {
  height: auto;
}

.panel-header {
  padding: 1vh 1.5vw;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #2d3a4b;
}

.panel-title {
  color: #bfcbd9;
  font-weight: bold;
  font-size: 0.75vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.collapse-icon {
  color: #8591a3;
  transition: transform 0.3s ease;
}

.collapse-icon.rotated {
  transform: rotate(-90deg);
}

.panel-content {
  padding: 0.6vh 0.8vw;
  max-height: 30vh;
  overflow-y: auto;
}

.layer-item {
  display: flex;
  flex-direction: column;
  gap: 0.3vw;
  margin-bottom: 0.8vh;
  padding: 0.3vh 0;
}

.layer-name {
  color: #bfcbd9;
  font-size: 0.7vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  gap: 0.3vw;
}

.layer-opacity {
  width: 100%;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.ol-map-container,
.cesium-map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

/* Cesium特殊样式 */
:deep(.cesium-widget) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.cesium-widget canvas) {
  width: 100% !important;
  height: 100% !important;
}

/* OpenLayers特殊样式 */
:deep(.ol-viewport) {
  width: 100% !important;
  height: 100% !important;
}

.coordinate-display {
  position: absolute;
  bottom: 1vw;
  left: 1vw;
  background: rgba(31, 45, 61, 0.95);
  border-radius: 0.6vw;
  padding: 0.8vh 1.2vw;
  display: flex;
  gap: 1.5vw;
  z-index: 1000;
  box-shadow: 0 0.4vw 1.2vw rgba(0, 0, 0, 0.3);
  max-width: 25vw;
}

.coord-item {
  display: flex;
  gap: 0.5vw;
}

.coord-label {
  color: #8591a3;
  font-size: 0.9vw;
}

.coord-value {
  color: #bfcbd9;
  font-size: 0.9vw;
  font-weight: bold;
  min-width: 4vw;
}

.draw-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1001;
  max-width: 30vw;
}

:deep(.el-radio-button__inner) {
  background: transparent;
  border-color: #2d3a4b;
  color: #bfcbd9;
  font-size: 0.9vw;
  padding: 0.8vh 1.5vw;
}

/* 地图模式切换按钮样式 */
.map-mode-switch :deep(.el-radio-button__inner) {
  background: rgba(45, 58, 75, 0.9) !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
  border-radius: 0.4vw !important;
  padding: 0.6vh 1vw !important;
  font-size: 0.75vw !important;
  transition: all 0.3s ease !important;
}

.map-mode-switch :deep(.el-radio-button__inner:hover) {
  background: rgba(64, 158, 255, 0.2) !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

.map-mode-switch :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background: linear-gradient(135deg, #409EFF, #67C23A) !important;
  border-color: #409EFF !important;
  color: #ffffff !important;
  box-shadow: 0 0.1vw 0.4vw rgba(64, 158, 255, 0.3) !important;
}

.toolbar-group :deep(.el-button) {
  height: 2vh !important;
  padding: 0 0.5vw !important;
  font-size: 0.8vw !important;
}

.toolbar-group :deep(.el-button:hover) {
  background: #2d3a4b;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-switch__core) {
  background: #2d3a4b;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background: #409EFF;
}

:deep(.el-slider__runway) {
  background: #2d3a4b;
}

:deep(.el-slider__bar) {
  background: #409EFF;
}

:deep(.el-alert) {
  background: rgba(31, 45, 61, 0.95);
  border-color: #409EFF;
}

:deep(.el-alert__title) {
  color: #bfcbd9;
}
</style>